package com.wy.supermarket.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wy.supermarket.entity.Supplier;
import com.wy.supermarket.repository.SupplierRepository;

@RestController
@RequestMapping("/supplier")
public class SupplierController {
	@Autowired //自动装载
	private SupplierRepository supplierRepository;
	
	@GetMapping("/findAll/{page}/{size}")
	public Page<Supplier> findAll(@PathVariable("page") Integer page,@PathVariable("size") Integer size){
		Pageable pageable=PageRequest.of(page-1, size);
		return supplierRepository.findAll(pageable);
	}
	
	@PostMapping("/addSupplier")
	public String addSupplier(@RequestBody Supplier supplier) {
		Supplier result=supplierRepository.save(supplier);
		if(result!=null) {
			return "sucess";
		}else {
			return "error";
		}
	}
	
	@GetMapping("/findById/{snum}")
	public Supplier findById(@PathVariable("snum") Integer snum) {
		return supplierRepository.findById(snum).get();
	}
	
	@GetMapping("/findByName/{sname}")
	public List<Supplier> findBySnameLike(@PathVariable("sname") String sname) { //模糊查询
		return supplierRepository.findBySnameLike("%"+sname+"%");
	}
	
	@PutMapping("/updateSupplier")
	public String updateSupplier(@RequestBody Supplier supplier) {
		Supplier result=supplierRepository.save(supplier);
		if(result!=null) {
			return "sucess";
		}else {
			return "error";
		}
	}
	
	@DeleteMapping("/deleteById/{snum}")
	public Supplier deleteById(@PathVariable("snum") Integer snum) {
		supplierRepository.deleteById(snum);
		return null;
	}

}


